package com.hiq.gene.model;

import com.hiq.gene.exception.InvalidTypeException;

import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

/**
 * @author Yanis_Triandaphilov
 */
public class Types {

    private static List<String> PLAIN_TYPES = Arrays.asList("string128", "string256", "string512",
            "string1024", "string2048", "string", "long", "int", "boolean", "datetime");

    private static Map<String, String> PG_MAPPING;
    private static Map<String, String> JAVA_MAPPING;

    static {
        PG_MAPPING = new Hashtable<String, String>();
        PG_MAPPING.put("string128",  "varchar(128)");
        PG_MAPPING.put("string256",  "varchar(256)");
        PG_MAPPING.put("string512",  "varchar(512)");
        PG_MAPPING.put("string1024", "varchar(1024)");
        PG_MAPPING.put("string2048", "varchar(2048)");
        PG_MAPPING.put("string",     "varchar(256)");
        PG_MAPPING.put("long",       "bigint");
        PG_MAPPING.put("int",        "int");
        PG_MAPPING.put("boolean",    "bool");
        PG_MAPPING.put("datetime",   "timestamp");

        JAVA_MAPPING = new Hashtable<String, String>();
        JAVA_MAPPING.put("string128",  "String");
        JAVA_MAPPING.put("string256",  "String");
        JAVA_MAPPING.put("string512",  "String");
        JAVA_MAPPING.put("string1024", "String");
        JAVA_MAPPING.put("string2048", "String");
        JAVA_MAPPING.put("string",     "String");
        JAVA_MAPPING.put("long",       "Long");
        JAVA_MAPPING.put("int",        "Integer");
        JAVA_MAPPING.put("boolean",    "Boolean");
        JAVA_MAPPING.put("datetime",   "Date");
    }

    private Types() { }

    public static String getPGType(String fieldType) throws InvalidTypeException {
        if (fieldType.startsWith("@")) {
            return "bigint";
        } else if (PG_MAPPING.containsKey(fieldType)) {
            return PG_MAPPING.get(fieldType);
        } else {
            throw new InvalidTypeException("No such type for postgresql: " + fieldType);
        }
    }

    public static String getJavaType(String type) throws InvalidTypeException {
        if (type.startsWith("@")) {
            return type.substring(1);
        } else if (JAVA_MAPPING.containsKey(type)) {
            return JAVA_MAPPING.get(type);
        } else {
            throw new InvalidTypeException("No such type for Java: " + type);
        }
    }

    public static boolean typeExists(String type) {
        return PLAIN_TYPES.contains(type);
    }
}
